/* eslint-disable eqeqeq */
// import { menuRoutes } from '@/router'
import { deepClone, arr2tree } from '@/utils'
// /**
//  * 处理动态路由菜单
//  * @param {*} list 数据
//  */
// export function filterMenuRoutes(filterMenu = []) {
//   const handleChild = (childList) => {
//     const list = []
//     childList.forEach((item) => {
//       if (item.meta?.menuCode) {
//         const { menuName } =
//           filterMenu.find((f) => f.menuCode === item.meta.menuCode) || {}
//         if (menuName) {
//           if (item.children?.length) {
//             item.children = handleChild(item.children)
//           }
//           list.push(item)
//         }
//       } else {
//         list.push(item)
//       }
//     })
//     return list
//   }
//   const menuList = handleChild(deepClone(menuRoutes))
//   return menuList
// }
/**
 * 处理动态路由菜单
 * @param {*} list 数据
 */
export function handlerMenuRoutes(filterMenu = []) {
  const newTree = deepClone(filterMenu).map((e) => {
    const {
      url,
      id,
      parentId,
      menuName: title,
      menuCode,
      type,
      routePath,
      icon,
      sort
    } = e
    let name = ''
    if (url.startsWith('#') || url.startsWith('http') || url.startsWith('@')) {
      name = url.startsWith('@') || url.startsWith('http') ? 'OutSidePage' : 'WeblinkPage'
    } else {
      name = capitalizeFirstLetter(routePath)
    }

    return {
      children: [],
      url,
      id,
      parentId,
      hidden: type == 3,
      sort,
      name,
      path: routePath,
      meta: {
        title,
        isKeepAlive: true,
        menuCode,
        icon,
        url,
        isBlank: ''
      }
    }
  })
  const menuTree = arr2tree(newTree, {
    id: 'id',
    parentId: 'parentId'
  })
  const AsyncMenu = filterAsyncRouter(menuTree)
  const newAsyncMenu = AsyncMenu.map((e) => {
    e.meta.isBlank = true
    return e
  })
  return newAsyncMenu.sort(function (a, b) {
    return a.sort - b.sort // 升序排序
  })
}

/**
 * 遍历后台传来的路由字符串，转换为组件对象
 * @param {*} asyncRouterMap
 * @returns
 */
function filterAsyncRouter(asyncRouterMap) {
  // console.log('后台传来的路由', asyncRouterMap)
  return asyncRouterMap.filter((route) => {
    const { url } = route
    if (url && (url.startsWith('@') || url.startsWith('#') || url.startsWith('http'))) {
      if (url.startsWith('#')) {
        route.component = () => require()
      } else {
        route.component = loadView(
          '/tools/outSidePage/index',
          route.hidden ? '' : route.name
        )
      }
    } else if (url) {
      // Layout组件特殊处理
      if (route.parentId === 'grass-boot') {
        route.component = loadView(url, route.hidden ? '' : route.name)
        route.path = '/' + route.path
      } else {
        route.component = loadView(url, route.hidden ? '' : route.name)
      }
    }
    if (route.children !== null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children).sort(function (a, b) {
        return a.sort - b.sort // 升序排序
      })
    }
    return true
  })
}

/**
 * 加载路由
 * @param {*} view
 * @param {*} name
 * @returns
 */
export const loadView = (view, name) => {
  // 路由懒加载
  return (resolve) => {
    return require([`@/views${view}`], (module) => {
      const component = {
        ...module.default,
        name
      }
      return resolve(component)
    })
  }
}

/**
 * 处理重定向问题
 * @param {*} list 数据
 */
// TODO 重定向问题
export function handlerRedirect(asyncMenu = []) {
  asyncMenu.forEach((e) => {
    if (e.children && e.children.length) {
      const idx = e.children.findIndex((item) => !item.hidden)
        if(idx !== -1){
          const childrenPath = e.children[idx].path
          if (childrenPath.includes('/')) {
            e.redirect = `${childrenPath}`
          } else {
            e.redirect = `${e.path}/${childrenPath}`
          }
        }
      handlerRedirect(e.children)
    }
  })
  return asyncMenu
}

/**
 * 首字母大写处理
 * @param {*} word
 * @returns
 */
export function capitalizeFirstLetter(word) {
  // 确保输入是字符串且非空
  if (typeof word !== 'string' || word.length === 0) {
    return word
  }

  // 将字符串拆分成单词数组
  const words = word.split(' ')

  // 对每个单词进行首字母大写处理
  const capitalizedWords = words.map((word) => {
    // 处理每个单词的首字母
    const firstLetter = word.charAt(0).toUpperCase()
    const restOfWord = word.slice(1)

    // 拼接首字母大写的单词
    return firstLetter + restOfWord
  })

  // 将处理后的单词数组拼接回字符串
  return capitalizedWords.join(' ')
}
